<template>
  <div class="AnnouncementManage-container">
    <el-input placeholder="请输入内容"
              style="width: 80%;"
              ref="multipleTable"
              @change="SearchAnnouncements"
              v-model="content">
      <i slot="prefix"
         class="el-input__icon el-icon-search"></i>
    </el-input>
    <div class="AnnouncementManage-table"
         v-if="announcementList.length">
      <el-table :data="announcementList"
                border
                stripe
                max-height="80%"
                :default-sort="{ prop: 'date', order: 'descending' }"
                @selection-change="handleSelectionChange"
                style="width: 100%">
        <el-table-column type="selection"
                         width="55">
        </el-table-column>
        <el-table-column label="创建日期"
                         sortable
                         width="180">
          <template slot-scope="scope">
            <svg-icon icon-class="date"></svg-icon>
            <span style="margin-left: 10px">{{ scope.row.create_time | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题"
                         width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.announcement_title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="浏览数">
          <template slot-scope="scope">
            <span>{{ scope.row.view_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         fixed="right">
          <template slot-scope="scope">
            <el-button size="mini"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination small
                     :page-size="limit"
                     @current-change="pageChange"
                     layout="prev, pager, next"
                     :total="count">
      </el-pagination>
    </div>
    <div v-else
         style="display:flex;justify-content:center">
      <img style="width:50%;margin:0 auto"
           src="@/assets/img/search-empty.png">
    </div>
    <EditDialog :data="EditForm"
                dialogTitle="编辑公告"
                :visible="EditDialogVisible"
                @custom-confirm="EditConfirm"
                @custom-close="EditDialogClose" />
    <div class="AnnouncementManage-batch-delete">
      <el-button type="danger"
                 size="mini"
                 @click="handleBatchDelete">批量删除</el-button>
    </div>
  </div>
</template>

<script>
import { encryptData } from "@/utils/encrypt";
import EditDialog from "@/components/Dialog/EditDialog";

export default {
  components: {
    EditDialog,
  },
  data () {
    return {
      limit: 10,
      page: 1,
      count: 0,
      announcementList: [],
      content: "",
      EditDialogVisible: false,
      formLabelWidth: "80px",
      distributeDialogVisible: false,
      EditForm: {},
      announcementList: [],
      selectedAnnouncements: [], // Newly added: to store selected announcements for batch deletion
    };
  },
  created () {
    this.$nextTick(() => {
      this.getAnnouncementList();
    });
  },
  methods: {
    // 多选项切换时
    handleSelectionChange (selection) {
      this.selectedAnnouncements = selection;
    },
    async getAnnouncementList () {
      const { limit, page } = this;
      const res = await this.$API.announcement.getAnnouncementList(limit, page);
      if (res.status == 200) {
        this.announcementList = res.data.payload;
        this.count = res.data.count;
      }
    },
    pageChange (page) {
      this.page = page;
      this.getAnnouncementList();
    },
    async handleEdit (id, announcement) {
      const res = await this.$API.announcement.getAnnouncementContent(announcement.id);
      if (res.status == 200) {
        let datas = {
          id: announcement.id,
          content: res.data.content,
          title: announcement.announcement_title,
          view_count: announcement.view_count,
        };
        this.EditForm = datas;
        this.EditDialogVisible = true;
      } else {
        return this.$message.error("公告不存在");
      }
    },
    handleDelete (id, announcement) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let datas = new FormData();
          datas.append("announcement_id", announcement.id);
          const res = await this.$API.announcement.DeleteAnnouncement(datas);
          if (res.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getAnnouncementList();
            this.content = "";
          } else {
            this.$message({
              type: "error",
              message: "删除失败!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async SearchAnnouncements () {
      this.page = 1;
      const { content, page, limit } = this;
      if (!this.content) return this.getAnnouncementList();
      const res = await this.$API.announcement.SearchAnnouncements(content, limit, page);
      if (!res.data) this.announcementList = [];
      if (res.status == 200) {
        this.announcementList = res.data.payload;
        this.count = res.data.count;
      }
    },
    EditDialogClose () {
      this.EditDialogVisible = false;
    },
    async EditConfirm (formData) {
      let { id, password, email } = formData;
      const datas = {
        announcement_id: id,
        ...formData,
      };
      const res = await this.$API.announcement.EditAnnouncement(this.$qs.stringify(datas));
      if (res.status == 200) {
        this.$message.success("编辑成功");
        this.EditDialogVisible = false;
        this.content = "";
        this.getAnnouncementList();
        this.EditForm = {};
      } else {
        this.$message.error("编辑失败");
      }
    },
    // 批量删除
    handleBatchDelete () {
      if (this.selectedAnnouncements.length === 0) {
        this.$message.warning("请选择要删除的公告");
        return;
      }

      this.$confirm("此操作将永久删除选中的公告, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const announcementIds = this.selectedAnnouncements.map((announcement) => announcement.id);
          const formData = new FormData();
          formData.append("announcement_ids", announcementIds.join(","));
          const res = await this.$API.announcement.BatchDeleteAnnouncement(formData);
          if (res.status === 200) {
            this.$message.success("批量删除成功");
            this.getAnnouncementList();
            this.content = "";
            this.selectedAnnouncements = [];
          } else {
            this.$message.error("批量删除失败");
          }
        })
        .catch(() => {
          this.$message.info("已取消批量删除");
        });
    },
  },
};
</script>

<style scoped>
.AnnouncementManage-container {
  width: 100%;
  padding: 20px;
}

.AnnouncementManage-table {
  width: 100%;
  margin: 10px auto;
}

.AnnouncementManage-batch-delete {
  margin-top: 10px;
  text-align: right;
}
</style>
